<template>
  <div class="variable-form">
    <el-card>
      <!-- // 面包屑 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>
          <a href="/">全局变量</a>
        </el-breadcrumb-item>
      </el-breadcrumb>
      <br />

      <!-- // 查询 -->
      <el-form
        ref="queryForm"
        :model="queryForm"
        size="small"
        :inline="true"
        label-width="80px"
      >
        <el-form-item label="变量名称" prop="name">
          <el-input
            clearable
            v-model="queryForm.name"
            placeholder="请输入变量名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadVariable()">查询</el-button>
          <el-button @click="handleResert">重置</el-button>
          <el-button type="success" @click="handleAdd()">新增</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格数据 -->
      <el-table
        :data="tableData"
        size="medium"
        border
        style="width: 100%"
        highlight-current-row
        v-loading="loading"
      >
        <el-table-column label="ID" type="index" width="50"> </el-table-column>
        <el-table-column prop="key" label="变量名" width="300">
        </el-table-column>
        <el-table-column prop="value" label="变量值" width="300">
        </el-table-column>
        <el-table-column prop="desc" label="描述" width="300">
        </el-table-column>
        <el-table-column prop="updator" width="120" label="更新人">
          <template slot-scope="scope">
            <el-tag effect="plain" size="">
              {{ scope.row.updator }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="update_time"
          :formatter="dateFormat"
          label="更新时间"
          width="250"
        >
        </el-table-column>

        <!-- // 操作按钮 -->
        <el-table-column label="操作" width="320" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="mini" @click="handleEdit(scope.row)"
              >编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.row.id)"
              >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <br />

      <!-- // 分页展示 -->
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        :page-sizes="[12, 20, 50, 100]"
        :total="pagination.total"
        :page-size="pagination.pageSize"
        :disabled="loading"
        :current-page.sync="pagination.page"
        @current-change="loadVariable(pagination.page)"
      >
      </el-pagination>
    </el-card>

    <!-- 新增变量弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      :modal-append-to-body="false"
      @close="dialogFormClosed"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="500px"
    >
      <el-form :model="dialogForm" :rules="dialogFormRules" ref="dialogFormRef">
        <el-form-item prop="key" label="变量名称" label-width="120px">
          <el-input
            clearable
            v-model="dialogForm.key"
            autocomplete="off"
            style="width:270px"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="value" label="变量值" label-width="120px">
          <el-input
            clearable
            v-model="dialogForm.value"
            autocomplete="off"
            style="width:270px"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="desc" label="描述" label-width="120px">
          <el-input
            clearable
            v-model="dialogForm.desc"
            autocomplete="off"
            style="width:270px"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addVariable,
  deleteVariable,
  updateVariable,
  queryVariable
} from "@/api/variable";
import moment from "moment";

export default {
  name: "",
  props: {},
  components: {},
  data() {
    return {
      // 筛选表单数据..
      queryForm: {
        name: undefined
      },
      loading: true,
      // 列表数据
      tableData: [],
      // 分页数据
      pagination: {
        total: 0,
        page: 1,
        pageSize: 12
      },
      // 表单名称
      title: "",
      // 添加和编辑表单的数据绑定对象
      dialogForm: {
        key: "",
        value: "",
        desc: ""
      },
      // 控制添加对话框的显示和隐藏
      dialogFormVisible: false,
      dialogFormRules: {
        key: [
          {
            required: true,
            message: "请输入变量名",
            trigger: "blur"
          },
          {
            max: 30,
            min: 1,
            message: "长度在 1 到 30 个字符",
            trigger: blur
          }
        ],
        value: [
          {
            required: true,
            message: "请输入变量值",
            trigger: "blur"
          },
          {
            max: 30,
            min: 1,
            message: "长度在 1 到 30 个字符",
            trigger: blur
          }
        ],
        desc: [
          {
            max: 50,
            min: 1,
            message: "长度在 1 到 50 个字符",
            trigger: blur
          }
        ]
      }
    };
  },
  computed: {},
  watch: {},
  created() {
    this.loadVariable();
  },
  mounted() {},
  methods: {
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.loadVariable();
    },

    // 获取全局变量数据
    loadVariable(page = 1) {
      this.loading = true;
      queryVariable({
        key: this.queryForm.name,
        page,
        page_size: this.pagination.pageSize,
        project_id: parseInt(window.localStorage.getItem("projectId"))
      }).then(res => {
        this.tableData = res.data.result;
        this.pagination.total = res.data.total;
        this.loading = false;
      });
    },

    // 重置表单
    dialogFormClosed() {
      this.$refs.dialogFormRef.resetFields();
      this.loadVariable();
    },

    // 重置筛选表单
    handleResert() {
      this.$refs["queryForm"].resetFields();
      this.loadVariable();
    },

    // 新增方法
    handleAdd() {
      this.dialogFormVisible = true;
      let projectId = parseInt(window.localStorage.getItem("projectId"));
      this.dialogForm = { project_id: projectId };
      this.title = "添加变量";
    },

    // 编辑方法
    handleEdit(rowData) {
      this.dialogFormVisible = true;
      this.title = "编辑变量";
      //使用深拷贝
      let form = JSON.parse(JSON.stringify(rowData));
      delete form.update_time;
      delete form.updator;
      this.dialogForm = form;
    },

    successMsg(msg) {
      this.$message({
        type: "success",
        message: msg
      });
    },

    // 弹窗表单处理
    submitForm() {
      // 校验表单
      this.$refs.dialogFormRef.validate(valid => {
        if (!valid) {
          return;
        }
        // 根据id是否为null判断是新增还是编辑
        if (this.dialogForm.id) {
          updateVariable(this.dialogForm)
            .then(res => {
              if (res.data.code === 200) {
                this.successMsg("更新成功");
              } else {
                this.$message.error(res.data.msg);
              }
              this.loadVariable(this.pagination.page);
            })
            .catch(err => {
              this.$message.error("更新失败:" + err);
            });
        } else {
          addVariable(this.dialogForm)
            .then(res => {
              if (res.data.code === 200) {
                this.successMsg("新增成功");
              } else {
                this.$message.error(res.data.msg);
              }
              this.loadVariable(this.pagination.page);
            })
            .catch(err => {
              this.$message.error("新增失败:" + err);
            });
        }
        // 关闭弹窗表单
        this.dialogFormVisible = false;
        // 重置表单，会自动刷新数据
        this.$refs.dialogFormRef.resetFields();
      });
    },

    // 编写日期格式化方法
    dateFormat: function(row, column) {
      const date = row[column.property];
      if (date === undefined) {
        return "";
      }
      // 这里的格式根据需求修改
      return moment(date).format("YYYY-MM-DD HH:mm:ss");
    },

    // 删除方法
    handleDelete(id) {
      {
        this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            deleteVariable({ id }).then(res => {
              this.successMsg("删除成功");
              this.loadVariable();
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          });
      }
    }
  }
};
</script>

<style></style>
